from jili.core.keyword import g_barbytick
from jili.core import moheengine as mh
import datetime
from jili.tool.state import ismongo,isredis
if isredis:
    import redis
    import pickle
    pool = redis.ConnectionPool(host='127.0.0.1')
    r = redis.Redis(connection_pool=pool)
if ismongo:
    pass
__subject="subbarbytick"
__unsubject="unsubbarbytick"
__pub="Barbytick"
__oncall={}
subkey={}
def __ondata(msg):
    p=msg["2"]
    p["timekey"]=datetime.datetime.strptime(p["timekey"], '%Y%m%d %H:%M:%S.%f')
    #print(p["timekey"])
    obj=p["obj"]
    if subkey[obj]<p["timekey"]:#去重  去老；只认最新行情
        if obj in __oncall.keys():
            for i in __oncall[obj]:
                i(p)
def subbarbytick(obj,barmode="1m",oncall=""):
    t={}
    t["obj"]=obj
    t["barmode"]=barmode
    if oncall!="":
        if obj not in __oncall.keys():
            __oncall[obj]=[]
            __oncall[obj].append(oncall)
            subkey[obj]=datetime.datetime.now()
            mh.subscribe(__ondata,__pub,obj)
        else:
            if oncall not in __oncall[obj]:
                __oncall[obj].append(oncall)
    return mh.safesend_sync(__subject,"",t)
def unsubbarbytick(obj,barmode="",oncall=""):
    t={}
    t["obj"]=obj
    t["barmode"]=barmode
    if obj in __oncall.keys():
        if oncall=="":
            del __oncall[obj]
            del subkey[obj]
        else:
            if oncall in __oncall[obj]:
                __oncall[obj].remove(oncall)
                if len(__oncall[obj])==0:
                    del __oncall[obj]
                    del subkey[obj]
        return mh.safesend_sync(__unsubject,"",t)
    else:
        return {"errcode":0,"info":{"info":""}}
def getbar(obj):
    if isredis:
        key = g_barbytick+obj
        p=r.get(key)
        if p:
            return pickle.loads(p)
        else:
            return {}
    else:
        return {}
